from inspect import signature
from pyexpat import model
from venv import create
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from datetime import timezone
from sqlalchemy import event  # 添加此行
from sqlalchemy.dialects.postgresql import UUID
import uuid  # 用于生成默认的 UUID 值

db = SQLAlchemy()


####################
#      用户表       #
####################
class User(db.Model):
    __tablename__ = "users"  # 明确指定表名
    # id = db.Column(db.Integer, primary_key=True)
    id = db.Column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )  # UUID 转字符串，长度固定为 36
    # id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)  # 使用 UUID 类型

    phone = db.Column(db.String(11), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))
    email = db.Column(db.String(128))

    avatar_url = db.Column(db.String(256), default="default_avatar.png")
    nickname = db.Column(db.String(64), default="网页用户")
    gender = db.Column(db.String(10), default="保密")
    signature = db.Column(db.Text, default="这个人很懒，什么都没有留下")
    long_term_memory = db.Column(db.TEXT, default="{}")  # 长期记忆

    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))

    def check_password(self, password):
        # 密码验证：前端明文 → 编码后与数据库哈希比较
        return bcrypt.checkpw(
            password.encode("utf-8"), self.password_hash.encode("utf-8")
        )


####################
#      会话表       #
####################
class Conversation(db.Model):
    __tablename__ = "conversations"
    id = db.Column(db.String(64), primary_key=True)  # 格式为conv_{uuid}
    user_id = db.Column(
        UUID(as_uuid=True), nullable=False
    )  # 与 users 表 id 关联，这里用 UUID 类型
    topic = db.Column(db.String(256))
    start_time = db.Column(db.DateTime, default=datetime.now(timezone.utc))
    last_active_time = db.Column(db.DateTime, default=datetime.now(timezone.utc))
    persona = db.Column(db.String(64), default="professional")

    # 可添加外键约束，关联到 User 表（如果需要严格的外键关联）
    __table_args__ = (db.ForeignKeyConstraint(["user_id"], ["users.id"]),)


####################
#     会话记录表     #
####################
class ConversationRecord(db.Model):
    __tablename__ = "conversation_records"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(UUID(as_uuid=True), nullable=False)  # 与 users 表 id 关联
    conversation_id = db.Column(
        db.String(64), nullable=False
    )  # 与 conversations 表 id 关联
    role = db.Column(db.String(10), nullable=False)
    content = db.Column(db.Text, nullable=False)
    message_id = db.Column(db.String(64), nullable=False)
    parent_message_id = db.Column(db.String(64))
    created_at = db.Column(db.DateTime, default=datetime.now(timezone.utc))
    model_metadata = db.Column(db.TEXT, default="")

    # 可添加外键约束，关联到 User 和 Conversations 表（如果需要严格的外键关联）
    __table_args__ = (
        db.ForeignKeyConstraint(["user_id"], ["users.id"]),
        db.ForeignKeyConstraint(["conversation_id"], ["conversations.id"]),
    )


class UserBuffer(db.Model):
    __tablename__ = "user_buffers"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(UUID(as_uuid=True), nullable=False)  # 与 users 表 id 关联
    conversation_id = db.Column(
        db.String(64), nullable=False
    )  # 与 conversations 表 id 关联
    role = db.Column(db.String(10), nullable=False)
    content = db.Column(db.Text, nullable=False)
    message_id = db.Column(db.String(64), nullable=False)
    parent_message_id = db.Column(db.String(64))
    # 修改 default 参数
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    model_metadata = db.Column(db.TEXT, default="")

    # 可添加外键约束，关联到 User 和 Conversations 表（如果需要严格的外键关联）
    __table_args__ = (
        db.ForeignKeyConstraint(["user_id"], ["users.id"]),
        db.ForeignKeyConstraint(["conversation_id"], ["conversations.id"]),
    )

    @classmethod
    def add_record(
        cls, user_id, conversation_id, role, content, message_id, parent_message_id=None
    ):
        try:
            new_record = cls(
                user_id=user_id,
                conversation_id=conversation_id,
                role=role,
                content=content,
                message_id=message_id,
                parent_message_id=parent_message_id,
            )
            db.session.add(new_record)

            # 检查当前会话的消息数量
            record_count = cls.query.filter_by(conversation_id=conversation_id).count()
            if record_count > 20:
                # 查询需要删除的最旧的消息
                oldest_records = (
                    cls.query.filter_by(conversation_id=conversation_id)
                    .order_by(cls.created_at.asc())
                    .limit(record_count - 20)
                )
                for record in oldest_records:
                    db.session.delete(record)

            db.session.commit()
            return new_record
        except Exception as e:
            # 出现异常时回滚事务
            db.session.rollback()
            print(f"添加记录时出错: {e}")
            return None


class EmotionRecord(db.Model):
    __tablename__ = "emotion_records"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(
        db.UUID(as_uuid=True),
        db.ForeignKey("users.id", ondelete="CASCADE"),
        nullable=False,
    )
    emotion = db.Column(db.String(50), nullable=False)
    content = db.Column(db.Text, nullable=False)
    summary = db.Column(db.Text)
    created_at = db.Column(db.DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
    ai_response = db.Column(db.Text)
    image_url = db.Column(db.String(256), default="")
    conversation_id = db.Column(db.String(64))


class PsychologicalAssessmentRecord(db.Model):
    __tablename__ = "psychological_assessment_records"

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.UUID(as_uuid=True), nullable=False)
    assessment_name = db.Column(db.String(100), nullable=False)
    results = db.Column(db.Text, nullable=False)
    ai_response = db.Column(db.Text)
    assessment_time = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)

    __table_args__ = (db.ForeignKeyConstraint(["user_id"], ["users.id"]),)
